/**
 * Created by rouzh on 2017-12-29.
 */
//测试连接数据库并显示全部
var express = require('express');
var bodyParser = require("body-parser");
//用body-parser模块解析前台post进来的值
var app = express();
var fs = require("fs");
var mysql  = require('mysql');
var UserSQL = {
    insert:'INSERT INTO user(account,password,id) VALUES(?,?,?)',
    bangding:'UPDATE user SET type = ?,openid = ? WHERE username = ? AND password = ? ',
    // queryAll:'SELECT * FROM user',
    getUserByOpenid:'SELECT * FROM user WHERE openid = ? ',
    getUserByInfo:'SELECT * FROM user WHERE account = ? AND password = ? ',
    deleteUserByInfo:'DELETE FROM user WHERE username = ? AND password = ? ',
};

app.use(bodyParser());
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended:true}));

app.use('/', express.static('E:/node/xinMusic'));

//处理跨域
app.all('*', function(req, res, next) {
    res.header("Access-Control-Allow-Origin", "*");
    res.header("Access-Control-Allow-Headers", "X-Requested-With");
    res.header("Access-Control-Allow-Methods","PUT,POST,GET,DELETE,OPTIONS");
    res.header("X-Powered-By",' 3.2.1');
    res.header("Content-Type", "application/json;charset=utf-8");
    next();
});

//连接数据库
var connection = mysql.createConnection({
    host     : 'localhost',
    user     : 'root',
    password : '123456',
    port: '3306',
    database: 'xinmusic',
});

connection.connect(function (err) {
    if(err){
        console.log(err);
    }
    else{
        console.log("连接成功");
    }
});

//获取所有歌曲
var selectSQL = 'select * from `music`';
var arr = [];
connection.query(selectSQL, function(err, rows) {
    if (err) throw err;
    for (var i = 0; i < rows.length; i++) {
        arr[i] = rows[i];
    }

    //把搜索值输出
    app.get('/Songs', function(req, res) {
        res.send(arr);
    });


});
// //关闭连接
// connection.end();
//不能多次使用end，应在应用结束后用


//登录接口
app.post('/login', function(req, res) {
    console.log(req.body);
    var account = req.body.account;
    var password = req.body.password;
    //输入验证
    if(!account || account == "") {
        console.log("用户名不能为空");
        res.send('用户名不能为空');
        return;
    }
    if(!password || password == "") {
        console.log("密码不能为空");
        res.send('密码不能为空');
        return;
    }
    connection.query('SELECT COUNT(*) checkNum FROM `user` WHERE account = \''+account+'\' AND password =\''+ password +'\'', function(err, rows, fields) {
        if (err) throw err;
        var checkNum = rows[0].checkNum;
        console.log('结果为: ', rows[0].checkNum);
        if(checkNum == 0){
            console.log('账号或密码不正确');
            res.send('账号或密码不正确');
        }else{
            res.send(account);
            console.log('登录成功！！！');
            //返回结果

        }
    });
     //关闭连接
    // connection.end();
});

// 注册页面
// app.get('/register', function (req, res) {
//     console.log(req.body);
//     var account = req.body.account;
//     var password = req.body.password;
//     var two_password = req.body.two_password;
//     //输入验证
//     if(!account || account == "") {
//         console.log("用户名不能为空");
//         res.send('用户名不能为空');
//         return;
//     }
//     if(!password || password == "") {
//         console.log("密码不能为空");
//         res.send('密码不能为空');
//         return;
//     }
//     if(password !== two_password) {
//         console.log("两次密码不一致");
//         res.send('两次密码不一致');
//         return;
//     }
//     console.log("/注册");
//     res.send('注册页面');
// })
// 注册接口
app.post('/register', function(req, res, next){
    console.log(req.body);
    var account = req.body.account;
    var password = req.body.password;
    var two_password = req.body.two_password;
    //输入验证
    if(!account || account == "") {
        console.log("用户名不能为空");
        res.send('用户名不能为空');
        return;
    }
    if(!password || password == "") {
        console.log("密码不能为空");
        res.send('密码不能为空');
        return;
    }
    if(password !== two_password) {
        console.log("两次密码不一致");
        res.send('两次密码不一致');
        return;
    }
    connection.query(UserSQL.getUserByInfo,[account,password],function (err, results){
        if (err){
            console.log(err)
            throw err
        }else{
            // 数据库不存在 就注册成功
            if (results.length == 0) {
                // 把新用户插入数据库
                connection.query(UserSQL.insert,[account,password,null],function (err, results) {
                    if(err){
                        throw err
                    }else{
                        res.end(JSON.stringify({status:'100',msg:'注册成功!'}));
                    }
                })
            } else{ // 数据库存在就注册失败
                res.end(JSON.stringify({status:'101',msg:'该用户名已经被注册'}));
            }
        }
    })
});


//  POST 请求
app.post('/', function (req, res) {
    console.log("主页 POST 请求");
    res.send('Hello POST');
})

//  /del_user 页面响应
app.get('/del_user', function (req, res) {
    console.log("/del_user 响应 DELETE 请求");
    res.send('删除页面');
})

//  /list_user 页面 GET 请求
// app.get('/list_user', function (req, res) {
//     console.log("/list_user GET 请求");
//     res.send('用户列表页面');
// })
app.get('/list_user', function (req, res) {
    fs.readFile( __dirname + "/" + "users.json", 'utf8', function (err, data) {
        console.log( data );
        res.send( data );
    });
    // res.send('用户列表页面lll');
})

// 对页面 abcd, abxcd, ab123cd, 等响应 GET 请求
app.get('/ab*cd', function(req, res) {
    console.log("/ab*cd GET 请求");
    res.send('正则匹配');
})


var server = app.listen(3000, function () {

    var host = server.address().address
    var port = server.address().port

    console.log("应用实例，访问地址为 http://127.0.0.1:%s", host, port)

})